package com.yun.baymax.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.yun.baymax.R;
import com.yun.baymax.activity.account.LoginActivity;
import com.yun.baymax.base.LocationHelper;
import com.yun.baymax.bean.ChatUser;
import com.yun.baymax.bean.User;
import com.yun.baymax.cache.ChatUserCache;
import com.yun.baymax.cache.UserCache;
import com.yun.baymax.fragment.AssistantFragment;
import com.yun.baymax.fragment.ConversationListFragment;
import com.yun.baymax.fragment.DiscoverFragment;
import com.yun.baymax.fragment.MoreFragment;
import com.yun.baymax.utils.DeviceUtils;
import com.yun.lib.utils.L;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;

import static cn.bmob.v3.BmobUser.getCurrentUser;

public class MainActivity extends BaseActivity {
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.more_lay)
    View moreLay;
    @BindView(R.id.more_press)
    ImageView moreImg;
    @BindView(R.id.discover_icon)
    ImageView discoverIcon;
    @BindView(R.id.notify_icon)
    ImageView notifyIcon;
    @BindView(R.id.message_icon)
    ImageView messageIcon;
    @BindView(R.id.view_pager)
    ViewPager viewPager;
    private ArrayList<Fragment> fragments = new ArrayList<>();
    private VpAdapter vpAdapter;
    private User bmUser;
    private boolean isFirstLogin;

    @Override
    protected int setLayoutResourceId() {
        return R.layout.activity_main;
    }

    @Override
    protected void initVariables() {
        LocationHelper.getInstance().startLocation();
        ButterKnife.bind(this);
        isFirstLogin = getIntent().getBooleanExtra("first", false);
        bmUser = BmobUser.getCurrentUser(User.class);
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {
        initViewPager();
    }

    private void initViewPager() {
        setSupportActionBar(toolbar);
        fragments.add(new ConversationListFragment());
        fragments.add(new AssistantFragment());
        fragments.add(new DiscoverFragment());
        fragments.add(new MoreFragment());
        vpAdapter = new VpAdapter(getSupportFragmentManager());
        viewPager.setAdapter(vpAdapter);
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                pagerSelected(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        viewPager.setOffscreenPageLimit(3);
        pagerSelected(0);
    }

    private void pagerSelected(int position) {
        switch (position) {
            case 0:
                messageIcon.setSelected(true);
                notifyIcon.setSelected(false);
                discoverIcon.setSelected(false);
                moreImg.setSelected(false);
                viewPager.setCurrentItem(0, false);
                toolbar.setTitle("会话");
                break;
            case 1:
                messageIcon.setSelected(false);
                notifyIcon.setSelected(true);
                discoverIcon.setSelected(false);
                moreImg.setSelected(false);
                viewPager.setCurrentItem(1, false);
                toolbar.setTitle("小秘");
                break;
            case 2:
                messageIcon.setSelected(false);
                notifyIcon.setSelected(false);
                discoverIcon.setSelected(true);
                moreImg.setSelected(false);
                viewPager.setCurrentItem(2, false);
                toolbar.setTitle("动态");
                break;
            case 3:
                messageIcon.setSelected(false);
                notifyIcon.setSelected(false);
                discoverIcon.setSelected(false);
                moreImg.setSelected(true);
                viewPager.setCurrentItem(3, false);
                toolbar.setTitle(bmUser.getNick());
                break;
            case 4:
                break;
            default:
                break;
        }
    }

    @Override
    protected void loadData() {
        //刷新用户数据
        BmobQuery<User> bmobQuery = new BmobQuery<User>();
        bmobQuery.addWhereEqualTo("username", getCurrentUser().getUsername());
        bmobQuery.findObjects(new FindListener<User>() {
            @Override
            public void done(List<User> list, BmobException e) {
                if (e == null) {
                    if (list != null && list.size() != 0) {
                        bmUser = list.get(0);
                        User bmob = BmobUser.getCurrentUser(User.class);
                        User currentUser = UserCache.getInstance().getCurrentUser();
                        User localUser = currentUser == null ? bmob : currentUser;
                        //检查是否在其他设备登录
                        if (!isFirstLogin && bmUser.getAndroidId() != null) {
                            if (!bmUser.getAndroidId().equals(DeviceUtils.getAndroidId())) {
                                Toast.makeText(MainActivity.this, "帐号已在其他设备登录", Toast.LENGTH_SHORT).show();
                                UserCache.getInstance().logOut();
                                goNext(null, LoginActivity.class);
                                finish();
                                return;
                            }
                        } else localUser.setAndroidId(DeviceUtils.getAndroidId());

                        UserCache.getInstance().saveBmobToLocal(bmUser, null);

                        ChatUser chatUser = ChatUserCache.getInstance().getChatUser(bmUser.getHxName());
                        chatUser.setHeadImage(bmUser.getHeadImage());
                        chatUser.setNick(bmUser.getUsername());
                        ChatUserCache.getInstance().updateChatUser(chatUser);
                    }
                } else {
                    L.i(e.getMessage());
                }
            }
        });
    }

    @OnClick({R.id.more_lay, R.id.notification_lay, R.id.message_lay, R.id.discover_lay})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.more_lay:
                pagerSelected(3);
                break;
            case R.id.notification_lay:
                pagerSelected(1);
                break;
            case R.id.message_lay:
                pagerSelected(0);
                break;
            case R.id.discover_lay:
                pagerSelected(2);
                break;
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onBackPressed() {
        if (toastBack()) {
            moveTaskToBack(true);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main_toolbar, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.add_trend:
                startActivity(new Intent(mContext, ChangeThemeAct.class));
                break;
            case R.id.add_friend:
                startActivity(new Intent(mContext, SearchActivity.class));
                break;
            case R.id.feedback:
                startActivity(new Intent(mContext, FeedbackActivity.class));
                break;
            case R.id.search_bar:
                startActivity(new Intent(mContext, PublishActivity.class));
                //仿哔哩搜索
//                SearchFragment searchFragment = new SearchFragment();
//                searchFragment.show(getSupportFragmentManager(), SearchFragment.TAG);
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    class VpAdapter extends FragmentPagerAdapter {
        public VpAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return fragments.get(position);
        }

        @Override
        public int getCount() {
            return fragments.size();
        }
    }
}
